package com.zgh.zhongcan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zgh.zhongcan.common.CustomException;
import com.zgh.zhongcan.entity.Category;
import com.zgh.zhongcan.entity.Dish;
import com.zgh.zhongcan.entity.Setmeal;
import com.zgh.zhongcan.mapper.CategoryMapper;
import com.zgh.zhongcan.service.CategoryService;
import com.zgh.zhongcan.service.DishService;
import com.zgh.zhongcan.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    /**
     * 根据id删除分类，删除前判断当前分类是否关联了 菜品 或者 套餐
     * @param id 分类id
     */
    @Override
    public void remove(Long id){
        //根据分类id查询dish（菜品）
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getCategoryId,id);
        int count1 = dishService.count(dishLambdaQueryWrapper);

        //根据分类id查询setmeal（套餐）
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper=new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);
        int count2 = setmealService.count(setmealLambdaQueryWrapper);
        //查询当前分类是否关联了菜品 或者 套餐 ，如果关联，抛出异常
        if(count1 > 0){//已经关联了菜品
            throw new CustomException("当前分类关联了菜品，不能删除");
        }else if (count2 > 0){//已经关联了套餐
            throw new CustomException("当前分类关联了菜品，不能删除");

        }

        //没有关联，正常删除分类
        super.removeById(id);


    }
}
